package com.daz.student.information.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import oracle.net.aso.q;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.daz.common.publicDict.pojo.publicDictPojo;
import com.daz.manager.loginHis.pojo.LoginHis;
import com.daz.manager.loginHis.server.impl.LoginHisSV;
import com.daz.student.information.pojo.StudentInfoPojo;
import com.daz.student.information.server.IStudentInfoSV;
import com.daz.student.pojo.studentPojo;
import com.daz.student.server.IStudentServer;
import com.daz.student.summary.pojo.SummaryPojo;
import com.daz.teacher.teacherInfo.pojo.TeacherInsertInfo;
import com.daz.teacher.teacherInfo.pojo.teacher;
import com.daz.teacher.teacherInfo.server.iTeacherServer;
import com.github.pagehelper.PageInfo;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class StudentInfoAction extends ActionSupport{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Autowired
	private IStudentServer studentServer;
	@Autowired
	private IStudentInfoSV studentInfoSV;
	@Autowired
	private iTeacherServer teacherServer;
	@Autowired
	private LoginHisSV sv;

	/**
	 * ǰ��̨��������
	 */
	private String studentIds;
	private String studentId;
	private String userName;
	private String Password;
	private String oldPassword;
	private String newPassword;
	private String teacherId;
	private Boolean success;
	private String grade;
	private String msg;
	private String idenTity;
	public String page;
	public String limit;
	public String query;
	private String uploadFileName;
	private String upload;
	private String photoPath;
	private String phone;
	private String email;
	private Date birth;
	private String politicalStatus;
	private String national;
	private String nativePlace;
	private String cardId;
	private String dorm;
	private String hobby;
	private String specialty;
	private String remark;
	private File file; 
	private int successNum;
	private int failureNum;
	private List failureList;
    private String uploadContentType;
	private PageInfo<StudentInfoPojo> resultList;
	private List<StudentInfoPojo> list;
	//private PageInfo<SummaryPojo> resultList;

	private List<String> isSelect = new ArrayList<>();
	private Map<String, Object> result = new HashMap<>(); 
	/**
	 * ��֤��¼
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String login(){
		LoginHis value = new LoginHis();
		value.setRole("3");
		value.setLoginDate(new Date());
		value.setAccount(userName);
		Map<String, Object> searchConditionMap = new HashMap<>();
		searchConditionMap.put("studentId", userName);
		searchConditionMap.put("password", Password);
		List<StudentInfoPojo> list=null;
		List<teacher> lists = null;
		Map<String, Object> session = ActionContext.getContext().getSession();
		try {
			list = studentInfoSV.searchStudentList(searchConditionMap);
			searchConditionMap.remove("password");
			lists = teacherServer.getTeacherInfo(searchConditionMap);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(null != list && list.size()>0){	
			StudentInfoPojo student= (StudentInfoPojo)list.get(0);
			session.put("userInfo",student);
			session.put("idenTity","student");
			session.put("userId",student.getStudentId());
			session.put("studentId",student.getStudentId().trim());
			session.put("userName",student.getStudentName());
			if(lists != null && lists.size() > 0){
				session.put("teacherId",lists.get(0).getTeacherId());
				session.put("teacherName",lists.get(0).getTeacherName());
			}
			this.setSuccess(true);
			value.setState("1");
			try {
				sv.insertSelective(value);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return "success";
		}
		else{
			this.setSuccess(false);
			this.setMsg("用户名或密码错误");
			value.setState("0");
			value.setExceptionTxt("用户名或密码错误");
			try {
				sv.insertSelective(value);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return "failed";
		}
	}
	public String index(){
		return SUCCESS;
	}
	
	public String logout(){
		Map<String, Object> session = ActionContext.getContext().getSession();
		session.remove("userInfo");
		session.remove("idenTity");
		session.remove("userId");
		session.remove("studentId");
		session.remove("userName");
		session.remove("teacherId");
		return SUCCESS;
	}
	
	public String qryStudentInfoById(){
		Map<String, Object> searchConditionMap = new HashMap<>();
		Map<String, Object> session = ActionContext.getContext().getSession();
		if(session != null){
			searchConditionMap.put("studentId", session.get("userId"));
			try {
				list=studentInfoSV.qryStudentById(searchConditionMap);
				this.setSuccess(true);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return SUCCESS;
	}
	
	
	public String changePassword(){
		Map<String, Object> searchConditionMap = new HashMap<>();	
		Map<String, Object> session = ActionContext.getContext().getSession();
		StudentInfoPojo info = (StudentInfoPojo)session.get("userInfo");
		
		if(info.getPassword().equals(oldPassword)){
			if(newPassword == null || "".equals(newPassword)) {
				this.setSuccess(false);
				this.setMsg("修改失败，新密码为空！");
			}
			searchConditionMap.put("studentId", session.get("userId"));
			searchConditionMap.put("password", newPassword);
			try {
				studentInfoSV.changePassWord(searchConditionMap);
				info.setPassword(newPassword);
				session.put("userInfo", info);
				this.setSuccess(true);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			this.setSuccess(false);
			this.setMsg("修改失败，原始密码错误！");
		}
		
		return SUCCESS;
	}
	
	public String photoPath(){
		Map<String, Object> session = ActionContext.getContext().getSession();
		studentId = (String)session.get("userId");
		String imgpath = "\\photo\\"+studentId+"\\";
		String path = ServletActionContext.getServletContext().getRealPath("/");
		return path+imgpath;
	}
	
	public String updateStudentPhoto(){
		String realPath =  photoPath()+	uploadFileName;	
        if (upload != null) {
        	File pathFile = new File(photoPath());
    		if(!pathFile.isDirectory()){
    			pathFile.mkdir();
    		}
    		else{
    			deleteFile(pathFile);
    		}
        	 try { 
        		 BufferedInputStream bis = new BufferedInputStream( 
                    new FileInputStream(upload)); 
        		 BufferedOutputStream bos = null; 
            
                bos = new BufferedOutputStream(new FileOutputStream(realPath));
                byte[] buff = new byte[8192]; 
                for (int len = -1; (len = bis.read(buff)) != -1;) { 
                    bos.write(buff, 0, len); 
                } 
                bos.flush(); 
                bis.close(); 
                bos.close();
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("photo", "photo/"+studentId+"/"+uploadFileName);
                map.put("studentId", ActionContext.getContext().getSession().get("studentId"));
                studentInfoSV.updateStudentInfo(map);
                this.setSuccess(true);
                this.setPhotoPath("photo/"+studentId+"/"+uploadFileName);
                
            } catch (Exception e) { 
                e.printStackTrace(); 
                this.setSuccess(false);
                this.setMsg("系统错误");
                return "failed"; 
                
            }
                                                                 
        } 
        else{
        	this.setSuccess(false);
            this.setMsg("请选择图片");
        }
		return SUCCESS;
	}
	
	public String deleteStudentPhoto(){
		
		Map<String, Object> map = new HashMap<String, Object>();
        map.put("photo", "");
        map.put("studentId", ActionContext.getContext().getSession().get("studentId"));
        try {
			studentInfoSV.updateStudentInfo(map);
			this.setSuccess(true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			this.setSuccess(false);
			this.setMsg("系统错误，删除失败！");
		}
        return SUCCESS;
		
	}
	
	public void deleteFile(File oldPath) {
        if (oldPath.isDirectory()) {
        
         File[] files = oldPath.listFiles();
         for (File file : files) {
           deleteFile(file);
         }
        }else{
          oldPath.delete();
        }
      }
	
	public String updateStudentInfo(){
		
		Map<String, Object> map = new HashMap<String, Object>();
		if(phone != null && !"".equals(phone)){
			map.put("phone", phone);
		}
		if(email != null && !"".equals(email)){
			map.put("email", email);
		}
		if(birth != null){
			map.put("birth", birth);
		}
		if(politicalStatus != null){
			map.put("politicalStatus", politicalStatus);
		}
		if(national != null){
			map.put("national", national);
		}
		if(nativePlace != null){
			map.put("nativePlace", nativePlace);
		}
		if(cardId != null){
			map.put("cardId", cardId);
		}
		if(dorm != null){
			map.put("dorm", dorm);
		}
		if(hobby != null){
			map.put("hobby", hobby);
		}
		if(specialty != null){
			map.put("specialty", specialty);
		}
		if(remark != null){
			map.put("remark", remark);
		}
		
        map.put("studentId", ActionContext.getContext().getSession().get("studentId"));
        try {
			studentInfoSV.updateStudentInfo(map);
			this.setSuccess(true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			this.setSuccess(false);
			this.setMsg("系统错误，保存失败！");
		}
		return SUCCESS;
	}
	
	public String searchAllStudentListPage(){
		int s=0;
		int l=0;
		if(page!=null){
			s = Integer.parseInt(page);
		}
		if(limit != null){
			l = Integer.parseInt(limit);
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		if(query != null){
			map.put("query",query);
		}
		try {
			resultList = studentInfoSV.searchStudentList(map, s, l);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	
	public String searchStudent(){
		Map<String, Object> searchMap = new HashMap<>();
		Map<String, Object> session = ActionContext.getContext().getSession();
		teacherId = (String)session.get("userId");
		searchMap.put("studentId", studentId);
		searchMap.put("teacherId", teacherId);
		try {
			list=studentInfoSV.searchStudentList(searchMap);
			this.setSuccess(true);
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			this.setSuccess(false);
			return ERROR;
		}
	}
	
	
	public String importStudents() throws Exception {
		
		/*String[] type={".xls",".xlsx"};
		Boolean flag=false;
        for(int i = 0;i<type.length;i++){
        	if(type[i].equals(uploadContentType)){
        		flag=true;
        		break;
        	}
        }
        if(!flag){
        	this.setSuccess(false);
        	this.setMsg("文件格式不真确，只支持.xls和.xlsx文件导入！");
        	return SUCCESS;
        }*/
        this.setSuccess(true);
        this.setSuccessNum(0);
        this.setFailureNum(0);
        file = new File("C:\\Users\\Administrator\\Desktop\\新建 Microsoft Office Excel 2007 Workbook.xlsx");
        /*//学生信息导入规则
         * 学号（SUTDENT_ID）、姓名(STUDENT_NAME)、性别(SEX)、年龄(AGO)、
         * 学院(ACADEMY)、专业(PROFESSIONAL)、年级(GRADE)、班级(INCLASS)、
         * 辅导员姓名(REMARK)、政治面貌(POLITICAL_STATUS)、籍贯(NATIVE_PLACE)
         */       
        if(file.isFile()){
        	InputStream input = null;
            try {
            	input = new FileInputStream(file);
            	XSSFWorkbook workBook;
            	workBook = new XSSFWorkbook(input);
				XSSFSheet sheet = workBook.getSheetAt(0);  
	            if (sheet != null)  
	            {  
	                for (int i = 1; i < sheet.getPhysicalNumberOfRows();i++)  
	                {  
	                	XSSFRow row = sheet.getRow(i);
	                	StudentInfoPojo value = new StudentInfoPojo();
	                    if(!"".equals(row.getCell(0).toString().trim())){
	                    	value.setStudentId(row.getCell(0).toString().trim());
	                    	value.setPassword(value.getStudentId());
	                    }else{
	                    	this.failureNum++;
	                    	failureList.add(i);
	                    	continue;
	                    	}
	                    
	                    if(!"".equals(row.getCell(1).toString().trim())){
	                    	value.setStudentName(row.getCell(1).toString().trim());
	                    }else{
	                    	this.failureNum++;
	                    	failureList.add(i);
	                    	continue;
	                    	}
	                    if("".equals(row.getCell(2).toString().trim())){
	                    	value.setSex(row.getCell(2).toString().trim());
	                    }
	                    if("".equals(row.getCell(3).toString().trim())){
	                    	value.setAgo(row.getCell(3).toString().trim());
	                    }
	                    if("".equals(row.getCell(4).toString().trim())){
	                    	value.setAcademy(row.getCell(4).toString().trim());
	                    }
	                    if("".equals(row.getCell(5).toString().trim())){
	                    	value.setProfessional(row.getCell(5).toString().trim());
	                    }
	                    if("".equals(row.getCell(6).toString().trim())){
	                    	value.setGrade(row.getCell(6).toString().trim());
	                    }
	                    if("".equals(row.getCell(7).toString().trim())){
	                    	value.setInclass(row.getCell(7).toString().trim());
	                    }
	                    if("".equals(row.getCell(8).toString().trim())){
	                    	value.setCounselor(row.getCell(8).toString().trim());
	                    }
	                    if("".equals(row.getCell(9).toString().trim())){
	                    	value.setPoliticalStatus(row.getCell(9).toString().trim());
	                    }
	                    if("".equals(row.getCell(10).toString().trim())){
	                    	value.setNativePlace(row.getCell(10).toString().trim());
	                    }
	                    studentInfoSV.importStudents(value);
	                    this.successNum++;
						}
	                //teacherServer.addTeacherBatch(teachersList);
	                this.setSuccess(true);
	                }
    		} catch (IOException e) {
    			e.printStackTrace();
    			this.setSuccess(false);
    		}
        }
        this.setSuccess(false);
        this.setMsg("文件解析失败！");
		return SUCCESS;
	}
	/*public String searchStudentByTeacherId(){
		int s=0;
		int l=0;
		if(page!=null){
			s = Integer.parseInt(page);
		}
		if(limit != null){
			l = Integer.parseInt(limit);
		}
		try {
			Map<String, Object> session = ActionContext.getContext().getSession();
			teacherId = (String)session.get("userId");
			Map<String, Object> searchConditionMap = new HashMap<String, Object>();
			searchConditionMap.put("teacherId", teacherId);
			if(query!=null && !"".equals(query)){
				searchConditionMap.put("query", query);
			}
			if(grade!=null && !"".equals(grade)){
				searchConditionMap.put("grade", grade);
			}
			resultList = studentInfoSV.searchStudentByTeacherId(searchConditionMap,s,l);
			this.setSuccess(true);
			return SUCCESS;
		} catch (Exception e) {			
			e.printStackTrace();
			this.setSuccess(false);
			return ERROR;
		}
	}
	public String searchStudentIsNotSelect(){
		try {
			Map<String, Object> map=new HashMap<>();
			if(query != null && !"".equals(query)){
				map.put("query", query);
			}
			if(grade != null && !"".equals(grade)){
				map.put("grade", grade);
			}
			list=studentInfoSV.searchStudentIsNotSelect(map);
			Map<String, Object> searchConditionMap = new HashMap<String, Object>();
			searchConditionMap.put("teacherId", teacherId);
			if(grade!=null && !"".equals(grade)){
				searchConditionMap.put("grade", grade);
			}
			resultList = studentInfoSV.searchStudentByTeacherId(searchConditionMap,0,0);
			if(resultList.getList().size()>0){
				for(int i=0;i<resultList.getList().size();i++){
					list.add(resultList.getList().get(i));
					isSelect.add(resultList.getList().get(i).getStudentId());
				}
			}
			result.put("list", list);
			result.put("isSelect", isSelect);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}*/
	
	public List<StudentInfoPojo> getList() {
		return list;
	}
	public void setList(List<StudentInfoPojo> list) {
		this.list = list;
	}
	public String getQuery() {
		return query;
	}
	public void setQuery(String query) {
		this.query = query;
	}
	public String getTeacherId() {
		return teacherId;
	}
	public void setTeacherId(String teacherId) {
		this.teacherId = teacherId;
	}
	
	public PageInfo<StudentInfoPojo> getResultList() {
		return resultList;
	}
	public void setResultList(PageInfo<StudentInfoPojo> resultList) {
		this.resultList = resultList;
	}
	public Boolean getSuccess() {
		return success;
	}

	public void setSuccess(Boolean success) {
		this.success = success;
	}
	
	public String getOldPassword() {
		return oldPassword;
	}
	public void setOldPassword(String oldPassword) {
		this.oldPassword = oldPassword;
	}
	public String getNewPassword() {
		return newPassword;
	}
	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getIdenTity() {
		return idenTity;
	}
	public void setIdenTity(String idenTity) {
		this.idenTity = idenTity;
	}
	public String getStudentId() {
		return studentId;
	}
	public void setStudentId(String studentId) {
		this.studentId = studentId;
	}
	public String getPassword() {
		return Password;
	}
	public void setPassword(String password) {
		Password = password;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public String getPage() {
		return page;
	}
	public void setPage(String page) {
		this.page = page;
	}
	public String getLimit() {
		return limit;
	}
	public void setLimit(String limit) {
		this.limit = limit;
	}
	public List<String> getIsSelect() {
		return isSelect;
	}
	public void setIsSelect(List<String> isSelect) {
		this.isSelect = isSelect;
	}
	public Map<String, Object> getResult() {
		return result;
	}
	public void setResult(Map<String, Object> result) {
		this.result = result;
	}
	public String getGrade() {
		return grade;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public void setGrade(String grade) {
		this.grade = grade;
	}
	public String getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public String getUpload() {
		return upload;
	}
	public void setUpload(String upload) {
		this.upload = upload;
	}
	public String getPhotoPath() {
		return photoPath;
	}
	public void setPhotoPath(String photoPath) {
		this.photoPath = photoPath;
	}
	public File getFile() {
		return file;
	}
	public void setFile(File file) {
		this.file = file;
	}
	public String getUploadContentType() {
		return uploadContentType;
	}
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	public int getSuccessNum() {
		return successNum;
	}
	public void setSuccessNum(int successNum) {
		this.successNum = successNum;
	}
	public int getFailureNum() {
		return failureNum;
	}
	public void setFailureNum(int failureNum) {
		this.failureNum = failureNum;
	}
	public List getFailureList() {
		return failureList;
	}
	public void setFailureList(List failureList) {
		this.failureList = failureList;
	}
	public Date getBirth() {
		return birth;
	}
	public void setBirth(Date birth) {
		this.birth = birth;
	}
	public String getPoliticalStatus() {
		return politicalStatus;
	}
	public void setPoliticalStatus(String politicalStatus) {
		this.politicalStatus = politicalStatus;
	}
	public String getNational() {
		return national;
	}
	public void setNational(String national) {
		this.national = national;
	}
	public String getNativePlace() {
		return nativePlace;
	}
	public void setNativePlace(String nativePlace) {
		this.nativePlace = nativePlace;
	}
	public String getCardId() {
		return cardId;
	}
	public void setCardId(String cardId) {
		this.cardId = cardId;
	}
	public String getDorm() {
		return dorm;
	}
	public void setDorm(String dorm) {
		this.dorm = dorm;
	}
	public String getHobby() {
		return hobby;
	}
	public void setHobby(String hobby) {
		this.hobby = hobby;
	}
	public String getSpecialty() {
		return specialty;
	}
	public void setSpecialty(String specialty) {
		this.specialty = specialty;
	}
	public String getRemark() {
		return remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}
	public String getStudentIds() {
		return studentIds;
	}
	public void setStudentIds(String studentIds) {
		this.studentIds = studentIds;
	}
	
}


